package org.erepublik.company.scanner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.bind.JAXBException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.erepublik.company.CompanyForSale;
import org.erepublik.company.ECountry;
import org.erepublik.company.EProductType;
import org.erepublik.company.License;
import org.erepublik.company.generated.CompanyT;
import org.erepublik.company.generated.ExportLicencesT;
import org.erepublik.company.generated.ExportLicenseT;
import org.erepublik.company.service.RawRegionsService;
import org.erepublik.company.utils.WebpageReader;
import org.erepublik.company.xml.XMLParsersers;

public class ErepublikHttpClient {

    private HttpClient client;
    private PostMethod method;
    private RawRegionsService rawRegionService;
    
    public ErepublikHttpClient(String login, String password, RawRegionsService rawRegionService) {
        client = new HttpClient();
        method = new PostMethod("http://www.erepublik.com/en/login");
        this.rawRegionService = rawRegionService;
        try {
            
            method.addParameter("citizen_name", login);
            method.addParameter("citizen_password", password);
            method.addParameter("comit", "Login");
            method.addParameter("_token", "f763a86bb213be3df08f25ca3f986a7f");
            client.executeMethod(method);

            System.out.println("login to erepublik as "+login);
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
    
    public ArrayList<CompanyForSale> getCompaniesForSale(ECountry country) {
        
        
        ArrayList<CompanyForSale> companylist = new ArrayList<CompanyForSale>();
        
        ArrayList<ErepublikCompanyForSaleSite> sites = getSites(country);
        for (ErepublikCompanyForSaleSite site : sites) {
            HashMap<Integer, Double> idsAndPrice = site.getCompaniesIdAndPrice();
            for (Integer erepublikCompanyForSaleSite : idsAndPrice.keySet()) {
                CompanyForSale companyForSale = getCompanyFromErepublikApi(erepublikCompanyForSaleSite);
                companyForSale.setPrice( idsAndPrice.get(erepublikCompanyForSaleSite) );
                companylist.add(companyForSale);
            }
        }
        
        return companylist;
    }

    
    
    
    private CompanyForSale getCompanyFromErepublikApi(Integer companyId) {
        try {
            CompanyT companyXml = XMLParsersers.parseCompany(
                    WebpageReader.getStreamToIrl("http://api.erepublik.com/v2/feeds/companies/"+companyId) );
            System.out.println("Scanning company "+companyId);
            CompanyForSale compnyForSale = new CompanyForSale();
            compnyForSale.setId(companyId);
            compnyForSale.setRegionName( companyXml.getRegion().getName() );
            compnyForSale.setEmployesNumber( companyXml.getEmployees().getEmployee().size() );
            compnyForSale.setCountry( ECountry.getCountryByName( companyXml.getCountry().getName() ) );
            compnyForSale.setName( companyXml.getName() );
            compnyForSale.setProductType( 
                    EProductType.getProductTypeByName( companyXml.getIndustry().getName() ) );
            compnyForSale.setQuality( companyXml.getCustomizationLevel() );
            compnyForSale.setRawSize( companyXml.getRawMaterialsInStock() );
            compnyForSale.setStockSize( companyXml.getStock() );
            compnyForSale.setRawRegion( rawRegionService.getRawRegion(compnyForSale.getProductType(), compnyForSale.getRegionName()) );
            
            if (companyXml.getEmployees()==null)
                compnyForSale.setEmployesNumber( 0 );
            else
                compnyForSale.setEmployesNumber( companyXml.getEmployees().getEmployee().size() );
            compnyForSale.setLicenses( getLincenses(companyXml.getExportLicenses()) );
            
            return compnyForSale;
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    
    
    private License[] getLincenses(ExportLicencesT exportLicenses) {

        ArrayList<License> licences = new ArrayList<License>();
        for (ExportLicenseT licence : exportLicenses.getExportLicense()) {
            License lic = new License();
            lic.setActive(licence.isIsActive());
            lic.setCountry( ECountry.getCountryByName( licence.getCountry().getName() ) );
            licences.add(lic);
        }
        
        return licences.toArray(new License[0]);
    }

    
    
    private ArrayList<ErepublikCompanyForSaleSite> getSites(ECountry country) {
        
        ArrayList<ErepublikCompanyForSaleSite> sites = new ArrayList<ErepublikCompanyForSaleSite>();
        
        boolean hasNext = true;
        int i=1;
        while (hasNext) {
            GetMethod method2 = new GetMethod("http://economy.erepublik.com/en/market/company/"+country.getErepublikId()+"/0/"+i);
            method2.setRequestHeader("Cookie", "erpk_auth=1&erpk=0bd023ff42af76e09a928d188e645bd1");
            try {
                
                client.executeMethod(method2);
                String response = method2.getResponseBodyAsString();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("skanuje kraj "+country+" strone " + "http://economy.erepublik.com/en/market/company/"+country.getErepublikId()+"/0/"+i);
           
                ErepublikCompanyForSaleSite site = new ErepublikCompanyForSaleSite(response);
                sites.add(site);
                hasNext = site.hasNextPage();
                i++;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sites;
    }
    
    
    

    
}
